import 'dart:convert';
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: CurrencyRatesScreen(),
    );
  }
}

class CurrencyRatesScreen extends StatelessWidget {
  // 假设这是你的 JSON 数据
  final String jsonData = '''{
    "result": "success",
    "documentation": "https://www.exchangerate-api.com/docs",
    "terms_of_use": "https://www.exchangerate-api.com/terms",
    "time_last_update_unix": 1734739201,
    "time_last_update_utc": "Sat, 21 Dec 2024 00:00:01 +0000",
    "time_next_update_unix": 1734825601,
    "time_next_update_utc": "Sun, 22 Dec 2024 00:00:01 +0000",
    "base_code": "USD",
    "conversion_rates": {
      "USD": 1,
      "AED": 3.6725,
      "AFN": 70.2765,
      "ALL": 93.8681,
      "AMD": 394.9423,
      "ANG": 1.79,
      "AOA": 930.7583,
      "ARS": 1025.42,
      "AUD": 1.6001,
      "AWG": 1.79,
      "AZN": 1.7002,
      "BAM": 1.8772,
      "BBD": 2.0,
      "BDT": 119.5092,
      "BGN": 1.8778,
      "BHD": 0.376,
      "BIF": 2932.54,
      "BMD": 1.0,
      "BND": 1.3563,
      "BOB": 6.926,
      "BRL": 6.1133,
      "BSD": 1.0,
      "BTN": 85.0693,
      "BWP": 13.7592,
      "BYN": 3.2786,
      "BZD": 2.0,
      "CAD": 1.4369,
      "CDF": 2843.9949,
      "CHF": 0.8934,
      "CLP": 992.1839,
      "CNY": 7.2976
    }
  }''';

  @override
  Widget build(BuildContext context) {
    // 解析 JSON 数据
    var data = jsonDecode(jsonData);
    var conversionRates = data['conversion_rates'];

    // 将转换率数据转换成 List
    List<Map<String, dynamic>> rateList = conversionRates.entries
        .map((entry) => {'currency': entry.key, 'rate': entry.value})
        .toList();

    return Scaffold(
      appBar: AppBar(
        title: Text('Currency Exchange Rates'),
      ),
      body: GridView.count(
        crossAxisCount: 2, // 设置每行显示两项
        padding: EdgeInsets.all(8.0),
        crossAxisSpacing: 8.0, // 行与列之间的间隔
        mainAxisSpacing: 8.0, // 主轴方向的间隔
        children: rateList.map((rate) {
          return Card(
            color: Colors.blue[50],
            elevation: 4.0,
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    rate['currency'], // 币种代码
                    style: TextStyle(
                      fontSize: 18.0,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  SizedBox(height: 8.0),
                  Text(
                    '${rate['rate'].toStringAsFixed(4)}', // 汇率值，保留4位小数
                    style: TextStyle(
                      fontSize: 16.0,
                    ),
                  ),
                ],
              ),
            ),
          );
        }).toList(),
      ),
    );
  }
}
